<template>
  <div class="pay-container">
    <!-- 生成微信支付二维码 -->
    <div class="erwei">
      <img :src="qrUrl" alt="" />
    </div>

    <!-- 微信图标 -->
    <svg class="icon" aria-hidden="true">
      <use xlink:href="#icon-wechat_pay"></use>
    </svg>
    <span>使用微信进行支付</span>

    <!-- 描述 -->
    <el-descriptions title="用户信息">
      <el-descriptions-item label="订单号">{{order_data.order_id}}</el-descriptions-item>
      <el-descriptions-item label="创建时间">{{order_data.create_time}}</el-descriptions-item>
      <el-descriptions-item label="产品名称">{{order_detail.productName}}</el-descriptions-item>
      <el-descriptions-item label="商品描述">{{order_detail.description}}</el-descriptions-item>
      <el-descriptions-item label="购买数量">{{order_detail.quantity}}</el-descriptions-item>
      <el-descriptions-item label="购买用户">{{order_data.user_nickname}}</el-descriptions-item>
      <el-descriptions-item label="地址">{{order_data.address}}</el-descriptions-item>
      <el-descriptions-item label="手机号">{{order_data.user_phone}}</el-descriptions-item>
      <el-descriptions-item label="总价格">{{order_data.total_fee}}</el-descriptions-item>
    </el-descriptions>
  </div>
</template>
<script>
import { mapState } from "vuex";
import qr from "qrcode"
import * as payApi from "@/api/pay";
export default {
  methods: {
    //使用定时器发送请求， 每一秒轮询支付结果
    queryOrderResult(){
      this.queryInterval=setInterval(async ()=>{
        let res= await payApi.queryOrderResult(this.order_id)
        console.log(res);
        if(res.data.status===200){
          //支付成功，跳转到支付成功的页面
          this.$router.push({name: "pay_success"})
        }
      },2000)
    }
  },
  data(){
    return { 
      order_data: {},
      order_detail: {},
      qrUrl: "",
      order_id: ""
    }
  },
  //通过订单id获取订单详情
  //根据订单id请求支付接口
  async created() {
    //console.log(this.$route);
    let order_id = this.$route.query.order_id;
    console.log(order_id);
    this.order_id=order_id
    //防止手动访问支付页面
    if(!order_id){
      this.$router.push("/vipmanager/charge")
      return;
    }
    let res = await Promise.all([
      payApi.queryOrderDetails(order_id),
      payApi.startPay(order_id),
    ]);
    //在发起支付之后，发起轮询查询支付结果
    this.queryOrderResult() 


    //console.log(res); 
    //订单详情赋值
    this.order_data=res[0].data.data
    //console.log(this.order_data);
    this.order_detail=res[0].data.data.orderDetail[0]
    //console.log(this.order_detail);
    //console.log(this.order_detail);


    //判断订单是否重复提交，如果重复提交则终止
    if(!res[1].data.state){
      this.$router.push("/vipmanager/charge")//返回充值页面
      return;
    }

    //下载qrcode插件，生成二维码
    let payUrl=res[1].data.code_url
    qr.toDataURL(payUrl,(err,imageBase64Url)=>{
      if(err){
        this.$messageBox.error(err)
        return
      }
      this.qrUrl=imageBase64Url
    })
  },
  //通过轮询，查询支付状态
  computed: {
    ...mapState(["currentProduct"]),
  },

  beforeDestroy(){
    //清空定时器 
    clearInterval(this.queryInterval)
  }
};
</script>